'use strict';

const codeMsg = {
  2001: '操作成功',
  2002: '登录成功',
  2003: '注册成功',
  2004: '已登录',
  2005: '已退出登录',

  4001: '请求参数错误',
  4002: '操作失败',
  4003: '请登录后操作',
  4004: '账号或密码错误',
  4005: '注册失败',
  4006: '已存在该账号',
  4007: '账号不存在',
  4008: '数据不存在',
};

module.exports = {
  errResult(code, result = null) {
    return {
      code: 2,
      message: codeMsg[code],
      messageCode: code,
      result,
    };
  },
  successResult(code, result = null) {
    return {
      code: 0,
      message: codeMsg[code],
      messageCode: code,
      result,
    };
  },
  listResult() {
    return {
      page: 0,
      pageSize: 0,
      data: [],
      total: 0,
    };
  },
  setLogin(value = {}) {
    const { ctx } = this;
    ctx.session.logintoken = value;
    const cookieOption = {
      httpOnly: false,
      signed: false,
    };
    ctx.cookies.set('loginstatus', '1', cookieOption);
    ctx.cookies.set('id', value.id, cookieOption);
    ctx.cookies.set('username', escape(value.username), cookieOption);
    ctx.cookies.set('role', value.role, cookieOption);
    ctx.cookies.set('nickname', escape(value.nickname), cookieOption);
  },
  getLogin() {
    const { ctx } = this;
    return ctx.session.logintoken;
  },
  removeLogin() {
    const { ctx } = this;
    ctx.session.logintoken = null;
    ctx.cookies.set('loginstatus', '0');
    ctx.cookies.set('id', null);
    ctx.cookies.set('username', null);
    ctx.cookies.set('role', null);
    ctx.cookies.set('nickname', null);
  },
  isLogin() {
    const { ctx } = this;
    if (ctx.session.logintoken) {
      return !!String(ctx.session.logintoken.id);
    }
    return false;
  },
};
